package com.cssy.yd.logic.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.authority.service.IScDepartmentService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.basic.service.IBasicCurrencyService;
import com.cssy.yd.basic.service.IBasicModeDeliveryService;
import com.cssy.yd.basic.service.IBasicModePaymentService;
import com.cssy.yd.logic.entity.LogicSkDO;
import com.cssy.yd.logic.entity.LogicSkItemDO;
import com.cssy.yd.logic.entity.LogicSoQuoteDO;
import com.cssy.yd.logic.entity.LogicSoQuoteProductDO;
import com.cssy.yd.logic.service.ILogicSoQuoteService;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
/**
 * 销售报价控制器
 * @author huang.xuming [2013-7-10]
 *
 */
@Controller
@RequestMapping("/yd/logic/soquote")
public class SoQuoteController extends BaseController<LogicSoQuoteDO> {
	private static final Logger logger = Logger.getLogger(SoQuoteController.class);

	private static final String MANAGER = "/yd/logic/soquote/SoQuoteManager";// 列表页面
	private static final String EIDT = "/yd/logic/soquote/SoQuoteOperation";// 添加、修改、显示页面

	@Resource(name = "logicSoQuoteService")
	ILogicSoQuoteService logicSoQuoteService;
	@Resource(name = "basicCurrencyService")
	private IBasicCurrencyService basicCurrencyService;
	@Resource(name="basicCompanyService")
	private IBasicCompanyService basicCompanyService;
	@Resource(name="basicModeDeliveryService")
	private IBasicModeDeliveryService basicModeDeliveryService;
	@Resource(name="basicModePaymentService")
	private IBasicModePaymentService basicModePaymentService;
	@Resource(name = "scDepartmentService")
    private IScDepartmentService scDepartmentService;
	

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}


	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		//scs.setPrefix("a1");//别名
		String cliNo =request.getParameter("cli_no");
		if(StringUtils.isNotEmpty(cliNo)){
			scs.addCondition("cli_no", cliNo);
		}
		hander.getWheres(scs);
		SearchResult result = logicSoQuoteService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
			
			//根据客户编号带出客户信息
			String cliNo = request.getParameter("cliNo");
			BasicCompanyDO bd = SoController.getClientBeanByNo(basicCompanyService, cliNo);
			if(null !=bd){
				LogicSoQuoteDO so = new LogicSoQuoteDO();
				so.setCliNo(bd.getCode());
				so.setCliName(bd.getName());
				so.setCliAddr(bd.getAddress());
				so.setCliPeo(bd.getAttachperson());
				so.setCliTel(bd.getTelephone());
				so.setCliFax(bd.getFax());
				model.addAttribute("so", so);
			}
			
		} else {
			LogicSoQuoteDO so = logicSoQuoteService.findListById(id);
			
			//List<LogicSoQuoteProductDO> soitem = logicSoQuoteService.findProductsByQuoteId(id);
			model.addAttribute("so", so);
			//model.addAttribute("soitem", soitem);
		}
		
		//查询汇率
		model.addAttribute("currency", SoController.getCurrencyList(basicCurrencyService));
		//支付方式
		model.addAttribute("payments",SoController.getPaymentList(basicModePaymentService));
		//交货方式
		model.addAttribute("deliveries",SoController.getDeliveryList(basicModeDeliveryService));
		//部门列表
		model.addAttribute("depts",SoController.getDepartmentList(scDepartmentService));
				
		
		//用户信息
		User user = SessionUtil.getUser(request);
		model.addAttribute("userRealName", user.getRealName());
		model.addAttribute("userName", user.getName());
		
		return EIDT;
	}

	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicSoQuoteProductDO> soitem = logicSoQuoteService.findProductsByQuoteId(id);
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSoQuoteDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("物料不能为空！");
				return bodyMap.modelMap;
			}
			logicSoQuoteService.soQuoteSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());

		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicSoQuoteDO ld = logicSoQuoteService.findListById(field);
				ld.setRemoved(1);
				logicSoQuoteService.update(ld, SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * ligerUI树的json
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheresNotLimit(scs);//不分页
		
		List<BasicCompanyDO> list =basicCompanyService.find(scs);
		
//		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
//		if(null != list){
//			for(BasicCompanyDO b : list){
//				Map<String, Object> itemMap = new HashMap<String, Object>();
//				itemMap.put("id",b.getCode());
//				itemMap.put("text",b.getName());
//				resultList.add(itemMap);
//			}
//		}
		
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	
	
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response,@RequestParam("soid") String soid, SearchConditions scs){
		//TODO
//		LogicSoQuoteDO sodo = logicSoQuoteService.findListById(soid);
////		List<LogicSoItemDO> sodoitems = logicSoQuoteService.findItemListBysoId(soid);
//		List<LogicSoQuoteProductDO> sodoitems = logicSoQuoteService.findProductsByQuoteId(soid);
//		response.setContentType("text/html;charset=UTF-8");
//		response.reset();
//		response.setContentType("application/ms-excel");
//		String fileNameDisplay = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//		try {
//			fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
//					"iso-8859-1");
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		}
//		fileNameDisplay = fileNameDisplay.replace(" ", "%20");
//		response.addHeader("Content-Disposition", "attachment;filename="
//				+ fileNameDisplay + ".xls");
//		OutputStream fout = null;
//		
//		HSSFWorkbook workbook = new HSSFWorkbook();
//		HSSFCellStyle cellStyle = workbook.createCellStyle();
//		cellStyle.setBorderBottom((short) 1);
//		cellStyle.setBorderLeft((short) 1);
//		cellStyle.setBorderRight((short) 1);
//		cellStyle.setBorderTop((short) 1);
//		cellStyle.setAlignment((short) 2);
//		cellStyle.setVerticalAlignment((short) 1l);
//		HSSFCellStyle title = workbook.createCellStyle();   
//		HSSFFont bold1 = workbook.createFont();
//		bold1.setFontName("黑体");
//		bold1.setFontHeightInPoints((short)16);
//		//bold1.setBoldweight((short) 50);
//		title.setFont(bold1);
//		title.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中      
//		title.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中   
//
//
//		
////		int colNum = 0;
//		HSSFSheet sheet = workbook.createSheet();
//		
//		HSSFCell cell = null ;
//		HSSFRow row = null ;
//		
//		row = sheet.createRow(0) ;
//		cell = row.createCell(0);
//		cell.setCellStyle(title);
//		cell.setCellValue(new HSSFRichTextString("送货签收单"));
//		//第1行
//		row = sheet.createRow(1) ;
//		row.setHeight((short)400);
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("客户编号："));
//		
//		cell = row.createCell(1);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString(sodo.getCliNo()));
//		
//		cell = row.createCell(2);
//		cell.setCellStyle(cellStyle);
//		
//		cell = row.createCell(3);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("送货编号："));
//		
//		cell = row.createCell(4);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString(""));
//		cell = row.createCell(5);
//		cell.setCellStyle(cellStyle);
//		
//		//第2行
//		row = sheet.createRow(2) ;
//		row.setHeight((short)400);
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("收货单位："));
//		
//		cell = row.createCell(1);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString(""));
//		
//		cell = row.createCell(2);
//		cell.setCellStyle(cellStyle);
//		
//		cell = row.createCell(3);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("送货日期："));
//		
//		cell = row.createCell(4);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString(""));
//		cell = row.createCell(5);
//		cell.setCellStyle(cellStyle);
//		
//	
//		//第3行
//		row = sheet.createRow(3) ;
//		row.setHeight((short)400);
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("送货地址："));
//				
//		cell = row.createCell(1);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString(sodo.getDeliveryAddr()));	
//		
//		for(int j = 2 ; j < 6 ; j++){
//			cell = row.createCell(j);
//			cell.setCellStyle(cellStyle);
//		}
//		//第四行
//		row = sheet.createRow(4) ;
//		row.setHeight((short)400);
//		
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("品名"));
//		
//		cell = row.createCell(1);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("品牌"));
//		
//		cell = row.createCell(2);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("单位"));
//		
//		cell = row.createCell(3);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("数量"));
//		
//		cell = row.createCell(4);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("件数"));
//		
//		cell = row.createCell(5);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("规格"));
//		int i = 0 ;
//		for( ; i < sodoitems.size() ; i ++){
//			row = sheet.createRow(5 + i) ;
//			row.setHeight((short)400);
//			cell = row.createCell(0);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(sodoitems.get(i).getProdName()));
//			
//			cell = row.createCell(1);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(""));
//			
//			cell = row.createCell(2);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(sodoitems.get(i).getProdUnit()));
//			
//			cell = row.createCell(3);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(sodoitems.get(i).getProdQuantity()+""));
//			
//			cell = row.createCell(4);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(sodoitems.get(i).getProdBQuantity()+""));
//			
//			cell = row.createCell(5);
//			cell.setCellStyle(cellStyle);
//			cell.setCellValue(new HSSFRichTextString(sodoitems.get(i).getProdSpecDesc()));
//		}
//		
//		row = sheet.createRow(5 + i) ;
//		row.setHeight((short)400);
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("备注："));
//		
//		for(int j = 1 ; j < 6 ; j++){
//			cell = row.createCell(j);
//			cell.setCellStyle(cellStyle);
//		}
//		
//		row = sheet.createRow(6 + i) ;
//		row.setHeight((short)600);
//		cell = row.createCell(0);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("收货单位及经手人（签章）："));
//		for(int j = 1 ; j < 3 ; j++){
//			cell = row.createCell(j);
//			cell.setCellStyle(cellStyle);
//		}		
//		cell = row.createCell(3);
//		cell.setCellStyle(cellStyle);
//		cell.setCellValue(new HSSFRichTextString("送货单位及经手人（签章）："));
//		for(int j = 4 ; j < 6 ; j++){
//			cell = row.createCell(j);
//			cell.setCellStyle(cellStyle);
//		}
//		
//		Region region = new Region((short)1,(short)1,(short)1 ,(short)2);//合并从第rowFrom行columnFrom列  
//		Region region1 = new Region((short)1,(short)4,(short)1 ,(short)5);//合并从第rowFrom行columnFrom列  
//		Region region2 = new Region((short)2,(short)1,(short)2 ,(short)2);//合并从第rowFrom行columnFrom列  
//		Region region3 = new Region((short)2,(short)4,(short)2 ,(short)5);//合并从第rowFrom行columnFrom列  
//		Region region4 = new Region((short)3,(short)1,(short)3 ,(short)5);//合并从第rowFrom行columnFrom列  
//		Region region5 = new Region((short)(5 + i),(short)1,(short)(5 + i),(short)5);//合并从第rowFrom行columnFrom列  
//		Region region6 = new Region((short)0,(short)0,(short)0 ,(short)5);//合并从第rowFrom行columnFrom列  
//		Region region7 = new Region((short)(6 + i),(short)0,(short)(6 + i) ,(short)2);//合并从第rowFrom行columnFrom列  
//		Region region8 = new Region((short)(6 + i),(short)3,(short)(6 + i) ,(short)5);//合并从第rowFrom行columnFrom列  
//		sheet.addMergedRegion(region);// 
//		sheet.addMergedRegion(region1);// 
//		sheet.addMergedRegion(region2);// 
//		sheet.addMergedRegion(region3);// 
//		sheet.addMergedRegion(region4);// 
//		sheet.addMergedRegion(region5);// 
//		sheet.addMergedRegion(region6);// 
//		sheet.addMergedRegion(region7);// 
//		sheet.addMergedRegion(region8);// 
//		sheet.setColumnWidth(0,3000); // 调整第一列宽度 
//		try {
//			fout = response.getOutputStream();
//			workbook.write(response.getOutputStream());
//			fout.flush();
//			fout.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

//	
//	@RequestMapping(value = "/soprinter")
//	public void deliverprinter(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicSoQuoteDO so=new LogicSoQuoteDO();
//			List<LogicSoItemDO> lp=new ArrayList<LogicSoItemDO>();
//			if(!"".equals(id)&&id!=null){
//				so = logicSoService.findListById(id);
//			
//			}
//			if(so.getId()!=null){
//				lp = logicSoServiceItem.findItemListBysoId(id);
//			}
//			int quan=0;int jquan=0;
//			if(lp.size()>0){
//				for(int i=0;i<lp.size();i++){
//					quan+=lp.get(i).getQuantity()==null?0:lp.get(i).getQuantity();
//					jquan+=lp.get(i).getJquantity()==null?0:lp.get(i).getJquantity();
//				}
//				request.setAttribute("so", so);
//				request.setAttribute("lp", lp);
//				request.setAttribute("quan", quan);
//				request.setAttribute("jquan", jquan);
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SoPrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
//	}
//	
//	@RequestMapping(value = "/sotprinter")
//	public void sotprinter(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicSoQuoteDO so=new LogicSoQuoteDO();
//			List<LogicSoItemDO> lp=new ArrayList<LogicSoItemDO>();
//			if(!"".equals(id)&&id!=null){
//				so = logicSoService.findListById(id);
//			
//			}
//			if(so.getId()!=null){
//				lp = logicSoServiceItem.findItemListBysoId(id);
//			}
////			int quan=0;int jquan=0;
//			if(lp.size()>0){
////				for(int i=0;i<lp.size();i++){
////					quan+=lp.get(i).getQuantity()==null?0:lp.get(i).getQuantity();
////					jquan+=lp.get(i).getJquantity()==null?0:lp.get(i).getJquantity();
////				}
//				request.setAttribute("so", so);
//				request.setAttribute("lp", lp);
//				request.setAttribute("row", lp.size());
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SotPrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
//	}
}
